// SearchService.java - 综合搜索服务
package com.search_wheel.service;

import com.search_wheel.pojo.entity.Content;
import com.search_wheel.pojo.entity.User;
import com.search_wheel.pojo.vo.SearchResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.util.ArrayList;
import java.util.List;

@Service
public class SearchService {

    @Autowired
    private ContentService contentService;

    @Autowired
    private UserService userService;

    /**
     * 综合搜索（同时搜索内容和用户）
     * 修复策略：优先填充内容结果，剩余位置给用户
     */
    public SearchResult<Object> searchAll(String keyword, int page, int size,String sort) {
        if (!StringUtils.hasText(keyword)) {
            return createEmptyResult(keyword, page, size);
        }

        // 修复方案1: 动态分配策略
        // 先获取总的可用结果数量来决定分配比例
        int totalContentCount = contentService.searchContent(keyword, 1, 1,sort).getTotal();
        int totalUserCount = userService.searchUser(keyword, 1, 1,sort).getTotal();

        int contentSize, userSize;

        if (totalUserCount == 0) {
            // 如果没有用户结果，全部分配给内容
            contentSize = size;
            userSize = 0;
        } else if (totalContentCount == 0) {
            // 如果没有内容结果，全部分配给用户
            contentSize = 0;
            userSize = size;
        } else {
            // 都有结果时，按比例分配，但确保内容至少占75%
            double contentRatio = (double) totalContentCount / (totalContentCount + totalUserCount);
            if (contentRatio < 0.75) {
                contentRatio = 0.75;
            }

            contentSize = Math.max(1, (int) (size * contentRatio));
            userSize = size - contentSize;
        }

        // 分别搜索内容和用户
        SearchResult<Content> contentResult = contentService.searchContent(keyword, page, contentSize,sort);
        SearchResult<User> userResult = userService.searchUser(keyword, page, userSize,sort);

        // 合并结果
        List<Object> allResults = new ArrayList<>();

        // 先添加内容结果
        if (contentResult.getData() != null) {
            allResults.addAll(contentResult.getData());
        }

        // 再添加用户结果
        if (userResult.getData() != null) {
            allResults.addAll(userResult.getData());
        }

        // 计算总数（修复：使用实际的总数）
        int total = contentResult.getTotal() + userResult.getTotal();

        return createSearchResult(allResults, total, page, size, keyword);
    }

    /**
     * 综合搜索的替代方案：纯内容优先策略
     */
    public SearchResult<Object> searchAllContentFirst(String keyword, int page, int size,String sort) {
        if (!StringUtils.hasText(keyword)) {
            return createEmptyResult(keyword, page, size);
        }

        // 计算实际需要的偏移量
        int offset = (page - 1) * size;

        // 首先尝试用内容填满整页
        SearchResult<Content> contentResult = contentService.searchContent(keyword, page, size,sort);

        List<Object> allResults = new ArrayList<>();
        if (contentResult.getData() != null) {
            allResults.addAll(contentResult.getData());
        }

        // 如果内容不足以填满一页，用用户结果补充
        int remainingSlots = size - allResults.size();
        if (remainingSlots > 0) {
            SearchResult<User> userResult = userService.searchUser(keyword, 1, remainingSlots,sort);
            if (userResult.getData() != null) {
                allResults.addAll(userResult.getData());
            }
        }

        // 获取总数
        int contentTotal = contentResult.getTotal();
        int userTotal = userService.searchUser(keyword, 1, 1,sort).getTotal();
        int total = contentTotal + userTotal;

        return createSearchResult(allResults, total, page, size, keyword);
    }

    /**
     * 根据类型搜索
     */
    public SearchResult<?> searchByType(String keyword, String type, int page, int size,String sort) {
        if (!StringUtils.hasText(keyword)) {
            return createEmptyResult(keyword, page, size);
        }

        switch (type.toLowerCase()) {
            case "content":
                return contentService.searchContent(keyword, page, size,sort);
            case "user":
                return userService.searchUser(keyword, page, size,sort);
            case "all":
            default:
                // 使用修复后的搜索方法
                return searchAllContentFirst(keyword, page, size,sort);
        }
    }

    /**
     * 搜索建议（简单实现，返回热门内容标题）
     */
    public List<String> getSearchSuggestions(String keyword, int limit,String sort) {
        if (!StringUtils.hasText(keyword) || keyword.length() < 2) {
            return List.of();
        }

        // 简单实现：返回包含关键词的热门内容标题
        SearchResult<Content> contents = contentService.searchContent(keyword, 1, limit,sort);
        return contents.getData().stream()
                .map(Content::getTitle)
                .toList();
    }

    private SearchResult<Object> createEmptyResult(String keyword, int page, int size) {
        SearchResult<Object> result = new SearchResult<>();
        result.setData(List.of());
        result.setTotal(0);
        result.setPage(page);
        result.setSize(size);
        result.setKeyword(keyword);
        result.setType("all");
        return result;
    }

    private SearchResult<Object> createSearchResult(List<Object> data, int total, int page, int size, String keyword) {
        SearchResult<Object> result = new SearchResult<>();
        result.setData(data);
        result.setTotal(total);
        result.setPage(page);
        result.setSize(size);
        result.setKeyword(keyword);
        result.setType("all");
        return result;
    }
}